package com.xdap.init.service.impl;

import com.xdap.api.moudle.formconfig.pojo.XdapFormConfig;
import com.xdap.common.dao.InitFormDao;
import com.xdap.init.dao.ModelDao;
import com.xdap.init.dao.ModelFeildDao;
import com.xdap.init.pojo.po.DataModel;
import com.xdap.init.pojo.po.DataModelField;
import com.xdap.init.service.InitModelFeildService;
import com.xdap.common.utils.InitDateFormatUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

@Slf4j
@Service
public class InitModelFeildServiceImpl implements InitModelFeildService {

    @Autowired
    private InitFormDao initFormDao;

    @Autowired
    private ModelFeildDao modelFeildDao;
    @Autowired
    private ModelDao modelDao;


    @Override
    public String initPoJava(String filePath, String tableName, String packageName, boolean hasPackageData) {
        List<DataModelField> fields = modelFeildDao.getFields(tableName);

        if (fields == null) {
            return "未能根据" + tableName + "获取到对应的模型";
        }
        DataModel model = modelDao.getModel(tableName);
        String formName = model.getModelName();


        String fileName = UpperStr(tableName);

        fileName = fileName.substring(0, 1).toUpperCase() + fileName.substring(1);
        String packageData = "package com.xdap.___packageName___.pojo.po;\n\n" +
                "import com.definesys.mpaas.query.annotation.Column;\n" +
                "import com.definesys.mpaas.query.annotation.Table;\n" +
                "import com.xdap.api.moudle.base.entity.XdapBasePojo;\n" +
                "import lombok.Data;\n" +
                "import java.util.Date;\n" +
                "/**\n" +
                "*@auth \n" +
                "*@Date " + InitDateFormatUtil.getCurrentYyyyMmDdHhMiSsCc() +
                "\n*@desc {" + formName + "}\n" +
                "**/" +
                "@Data\n" +
                "@Table(\"" + tableName + "\")\n" +
                "public class " + fileName + " extends XdapBasePojo { \n";
        String data = "";
        if (hasPackageData) {
            data += packageData;
        }
        data += "\t@Column(\"id\") \n\tprivate String id; \n" +
                "\t@Column(\"document_id\") \n\tprivate String documentId; \n" +
                "\t@Column(\"tab_doc_id\") \n\tprivate String tabDocId; \n" +
                "\t@Column(\"status\") \n\tprivate String status; \n \n\n";

        data = data.replaceAll("___packageName___", packageName);
        data = getData(fields, data, true);
        if (hasPackageData) {
            data += "}";
        }
        String result = createJava(filePath, fileName, data);

        result += initVoJava(filePath, tableName, packageName, fields, formName);
        return result;
    }


    @Override
    public String getData(List<DataModelField> fields, String data, boolean isPo) {

        for (DataModelField field : fields) {
            // 注释
            String fieldComment = field.getFieldComment();
            String fieldName = field.getFieldName();
            String fieldCode = field.getFieldCode();
            String targetName = UpperStr(fieldCode);
            String fieldStatus = field.getFieldStatus();

            if ("DISABLE".equals(fieldStatus)) {
                data += "\t// " + fieldCode + "数据库字段" + targetName + "已经禁用\n";
            } else {
                // 类型
                String col3 = field.getFieldType();
                if (col3.equals("DATE")) {
                    col3 = "\tprivate Date ";
                } else if ((col3.equals("NUM"))) {
                    col3 = "\tprivate Double ";
                } else {
                    col3 = "\tprivate String ";
                }
                data += "\t/*\n" +
                        "\t *@desc {" + fieldName + ":" + fieldComment + "}\n" +
                        "\t */\n";
                if (isPo) {
                    data += "\t@Column(\"" + fieldCode + "\") \n";
                }
                data += col3 + targetName + "; \n\n";
            }

        }
        return data;
    }

    /**
     * @auth lishushu
     * @2023/4/17 17:41
     * @desc {vo的数据是往外部传送的，所以不会校验vo的数据是不是和数据库的一致}
     **/
    public String initVoJava(String filePath, String tableName, String packageName, List<DataModelField> fields,
                             String formName) {

        if (fields == null) {
            return "未能根据" + tableName + "获取到对应的模型";
        }
        String fileName = UpperStr(tableName);

        fileName = fileName.substring(0, 1).toUpperCase() + fileName.substring(1);
        String data = "package com.xdap.___packageName___.pojo.vo;\n" +
                "import com.definesys.mpaas.query.annotation.Column;\n" +
                "import com.definesys.mpaas.query.annotation.Table;\n" +
                "import com.xdap.api.moudle.base.entity.XdapBasePojo;\n" +
                "import lombok.Data;\n" +
                "import java.util.Date;\n" +
                "/**\n" +
                "*@auth \n" +
                "*@Date " + InitDateFormatUtil.getCurrentYyyyMmDdHhMiSsCc() +
                "\n*@desc {" + formName + "}\n" +
                "**/" +
                "@Data\n" +
                "public class " + fileName + " { \n" +
                "\tprivate String documentId; \n" +
                "\tprivate String tabDocId; \n" +
                "\tprivate String status; \n \n\n";

        data = data.replaceAll("___packageName___Vo", packageName);
        getData(fields, data, false);

        data += "}";
        String result = createJava(filePath, fileName, data);
        return result;
    }


    @Override
    public String initDaoJava(String filePath, String tableName, String packageName) {
        // 查询model表，查询resource表，确认当前的表是自带默认数据源还是外部数据源 TODO 接下来只做内部数据源的处理
        String fileName = UpperStr(tableName);
        String fileNameUpper = fileName.substring(0, 1).toUpperCase() + fileName.substring(1);
        String data = "package com.xdap.___packageName___.dao;\n" +
                "import com.definesys.mpaas.query.MpaasQuery;\n" +
                "import com.xdap.motor.utils.StringUtils;\n" +
                "import com.xdap.runtime.service.RuntimeDatasourceService;\n" +
                "import lombok.RequiredArgsConstructor;\n" +
                "import org.springframework.beans.factory.annotation.Value;\n" +
                "import org.springframework.stereotype.Repository;\n" +
                "import java.util.List;\n" +
                "@Repository\n" +
                "@RequiredArgsConstructor\n" +
                "public class ____FILENAME_UPPER___Dao {\n" +
                "    private final RuntimeDatasourceService runtimeDatasourceService;\n" +
                "    @Value(\"${spring.datasource.name}\")\n" +
                "    private String tenantSchema;\n" +
                "    public void insert____FILENAME_UPPER___(____FILENAME_UPPER___ ____FILENAME___) {\n" +
                "        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);\n" +
                "        mpaasQuery.table(\"___TABLENAME___\");\n" +
                "        mpaasQuery.doInsert(____FILENAME___);\n" +
                "    }\n" +
                "    public void update____FILENAME_UPPER___(____FILENAME_UPPER___ ____FILENAME___) {\n" +
                "        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);\n" +
                "        mpaasQuery.eq(\"id\", ____FILENAME___.getId());\n" +
                "        mpaasQuery.table(\"___TABLENAME___\");\n" +
                "        mpaasQuery.doUpdate(____FILENAME___);\n" +
                "    }\n" +
                "    public void delete____FILENAME_UPPER___(____FILENAME_UPPER___ ____FILENAME___) {\n" +
                "        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);\n" +
                "        mpaasQuery.eq(\"id\", ____FILENAME___.getId());\n" +
                "        mpaasQuery.table(\"___TABLENAME___\");\n" +
                "        mpaasQuery.doDelete(____FILENAME___);\n" +
                "    }\n" +
                "    public void delete____FILENAME_UPPER___ByData(String data) {\n" +
                "        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);\n" +
                "        mpaasQuery.eq(\"data\", data); // TODO 需要修改对应的判断条件\n" +
                "        mpaasQuery.table(\"___TABLENAME___\");\n" +
                "        mpaasQuery.doDelete(____FILENAME___);\n" +
                "    }\n" +
                "    public ____FILENAME_UPPER___ get____FILENAME_UPPER___(String data) {\n" +
                "        if (data == null || StringUtils.isBlank(data + \"\")) {\n" +
                "            return null;\n" +
                "        }\n" +
                "        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);\n" +
                "        mpaasQuery.eq(\"data\", data); // TODO 需要修改对应的判断条件 \n" +
                "        mpaasQuery.table(\"___TABLENAME___\");\n" +
                "        ____FILENAME_UPPER___ ____FILENAME___ = mpaasQuery.doQueryFirst(____FILENAME_UPPER___.class);\n" +
                "        return ____FILENAME___;\n" +
                "    }\n" +
                "    public List<____FILENAME_UPPER___> getAll____FILENAME_UPPER___() {\n" +
                "        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(tenantSchema);\n" +
                "        mpaasQuery.ne(\"id\", \"0\");\n" +
                "        mpaasQuery.table(\"___TABLENAME___\");\n" +
                "        List<____FILENAME_UPPER___> ____FILENAME___list = mpaasQuery.doQuery(____FILENAME_UPPER___.class);\n" +
                "        return ____FILENAME___list;\n" +
                "    }\n" +
                "}";
        data = data.replaceAll("___packageName___", packageName);
        log.info("data:{}", data);
        data = data.replaceAll("____FILENAME___", fileName);
        data = data.replaceAll("____FILENAME_UPPER___", fileNameUpper);
        data = data.replaceAll("___TABLENAME___", tableName);
        return createJava(filePath, fileNameUpper + "Dao", data);
    }



    private String UpperStr(String fieldCode) {
        String targetName = "";
        boolean upper = false;
        if (fieldCode.contains("_")) {
            String colDataC = "";
            char[] chars = fieldCode.toCharArray();
            for (char c : chars) {
                colDataC = c + "";
                if ('_' == c) {
                    upper = true;
                } else {
                    if (upper) {
                        colDataC = colDataC.toUpperCase();
                        upper = false;
                    }
                    targetName += colDataC;
                }
            }
        } else {
            targetName = fieldCode;
        }

        return targetName;
    }

    @Override
    @SneakyThrows
    public String createJava(String filePath, String fileName, String data) {
        FileOutputStream outstream = null;
        int ch;
        byte[] bytes = new byte[1024];
        ByteArrayInputStream inputStream = null;
        if (!fileName.endsWith(".java")) {
            fileName = fileName + ".java";
        }
        try {
            //写入文件
            outstream = new FileOutputStream(filePath + File.separator + fileName);
            inputStream = new ByteArrayInputStream(data.getBytes("UTF-8"));
            while ((ch = inputStream.read(bytes)) != -1) {
                //数据写在文件夹里
                outstream.write(bytes, 0, ch);
            }
            return "本地文件创建成功:" + filePath + File.separator + fileName;
        } catch (Exception e) {
            log.error("本地创建文件失败" + filePath + File.separator + fileName);
            e.printStackTrace();
            return "本地创建文件失败" + filePath + File.separator + fileName;
        } finally {
            if (outstream != null) {
                outstream.flush();
                outstream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    @Override
    public String initPoJava(String filePath, String formId, String packageName) {
        // 根据formId获取应该初始化的表信息
        XdapFormConfig xdapFormConfig = initFormDao.getXdapFormConfig(formId);

        return initPo(filePath, xdapFormConfig, packageName);
    }

    public String initPo(String filePath, XdapFormConfig xdapFormConfig, String packageName) {


        // 根据表信息更新 model 和 model_field 的注释和备注

        // 获取本地模板，对模板进行更新操作

        return null;
    }


}